<?php
class Publication{
	/**
	 * Enter description here...
	 *
	 * @var Mysql
	 */
	private $db;
	
	public function __construct($db)
	{
		$this->db = $db;
	}
	
	public function add( array $value)
	{
		$arr_info = AdminUser::getLoginInfo();
		$v = array();
		$v['typeid'] = $value['typeid'];
		$v['name'] = $value['name'];
		$v['author'] = $value['author'];
		$v['keywords'] = $value['keywords'];
		$v['intro'] = $value['intro'];
		$v['image'] = $value['image'];
		$v['pdf'] = $value['pdf'];
		$v['down'] = $value['down'];
		$v['seq'] = $value['seq'];
		$v['adminid'] = $arr_info['id'];
		
		$pid = $this->db->insert("publication", $v, true);
			
		$this->updateGroupCache();
		
		return $pid;
	}
	
	
	public function change($pid, array $value)
	{
		$v = array();
		
		isset($value['typeid']) && $v['typeid'] = $value['typeid'];
		isset($value['name']) && $v['name'] = $value['name'];
		isset($value['author']) && $v['author'] = $value['author'];
		isset($value['keywords']) && $v['keywords'] = $value['keywords'];
		isset($value['intro']) && $v['intro'] = $value['intro'];
		isset($value['image']) && $v['image'] = $value['image'];
		isset($value['pdf']) && $v['pdf'] = $value['pdf'];
		isset($value['down']) && $v['down'] = $value['down'];
		isset($value['seq']) && $v['seq'] = $value['seq'];

		$this->db->update("publication", $v, 'pid=' . $pid);
		$this->updateGroupCache();
	}
	
	public function del($pid)
	{
		$this->db->delete("publication", 'pid=' . $pid);
		$this->updateGroupCache();
	}
	
	
	/**
	 * 读取文章列表
	 *
	 * @param Integer $nowp
	 * @param Integer $per_page
	 */
	public function listPublicationByWhere($where, $nowp, $per_page)
	{		
		 $totalNum = $this->db->fetchOne ('select count(*) from publication ' . $where);
        
        require_once APP . '/application/models/Util.php';
        
        $pageInfo = Util::page ($totalNum, $per_page, $nowp);
        $start    = $pageInfo ['start'];
        $list     = $this->db->fetchAll ('select t1.*,t2.name as typename, t3.username from publication t1
        left join alllist t2 on t2.id=t1.typeid
        left join admin t3 on t3.id=t1.adminid
		' . $where . '
        order by seq desc,pid desc limit ' . $start . ',' . $per_page);
        
        return Array ('page' => $pageInfo['page'], 'list' => $list);
	}
	
	private function updateGroupCache()
	{
		
	}
	
	public function show($pid)
	{
		return $this->db->fetchRow("select * from publication where pid=\"?\"", array($pid));
	}
}